package cn.com.jrr.core.controller;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.com.jrr.core.common.StringUtils;
import cn.com.jrr.core.common.ToolUtils;
import cn.com.jrr.core.model.DataTableRequest;
import cn.com.jrr.core.model.DataTableResponse;
import cn.com.jrr.core.model.ResponseMessage;
import cn.com.jrr.core.model.power.SysUser;
import cn.com.jrr.core.service.power.SysUserService;


@Controller
@RequestMapping("/user")
public class SysUserController {
    @Autowired
    private SysUserService sysUserService;
    private DataTableResponse<SysUser> dt;
    @Autowired
    private ResponseMessage responseMessage;
    private SysUser sysUser;

    @RequestMapping("/user")
    public String user(){
        return "/power/user";
    }

    @ResponseBody
    @RequestMapping("/userList")
    public DataTableResponse<SysUser> userlist(DataTableRequest dataTableRequest){
        dt=sysUserService.list(dataTableRequest);
        return dt;
    }


    /**
     * 添加用户信息
     */
    @ResponseBody
    @RequestMapping("/saveaddupdate")
    @Transactional
    public ResponseMessage userAdd(SysUser sysUser){
        try{
            if(sysUser.getUserId()==null || "".equals(sysUser.getUserId().toString())){
                sysUser.setEntrydt(new Date());
                sysUserService.add(sysUser);
            }else{
                sysUser.setUpdatedt(new Date());
                sysUserService.update(sysUser);
            }
            responseMessage.setStatus("success");
        }catch(Exception e){
            responseMessage.setStatus("fail");
        }

        return responseMessage;
    }

    /**
     * 获取单个用户
     */
    @ResponseBody
    @RequestMapping("/get")
    public SysUser userGet(@RequestParam Integer id){
        sysUser=sysUserService.get(id);
        return sysUser;
    }
    /**
     * 删除用户
     */
    @ResponseBody
    @RequestMapping("/delete")
    public ResponseMessage userDelete(@RequestParam String idString){
        List<Integer> idList=ToolUtils.splitIdString(idString);
        for(Integer id:idList){
            sysUserService.delete(id);
        }
        responseMessage.setStatus("success");
        return responseMessage;
    }

    @ResponseBody
    @RequestMapping("/userListByroleId")
    public DataTableResponse<SysUser> userListByroleId(DataTableRequest dataTableRequest,Integer roleId){
        dt=sysUserService.userListByRoleId(dataTableRequest,roleId);
        return dt;
    }

}
